package com.practice.xml.dom;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public final class XmlTransformerFactoryPractice {
	public static void run() {
		TransformerFactory tf = TransformerFactory.newInstance();
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try {
			Transformer t = tf.newTransformer();
			t.setOutputProperty(OutputKeys.INDENT, "yes");
			
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.newDocument();
			
			Element booklist = document.createElement("booklist");
			document.appendChild(booklist);
			
			booklist.appendChild(createBook(document, "AAA", "aaa", 0xAA));
			booklist.appendChild(createBook(document, "BBBB", "bbb", 0xBB));
			
			t.transform(new DOMSource(document), new StreamResult(System.out));
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
	
	private static Element createBook(Document document, String name, String author, int price) {
		Element book = document.createElement("book");
		
		Attr priceAttr = document.createAttribute("price");
		priceAttr.setValue(new Integer(price).toString());
		
		Element nameElment = document.createElement("name");
		nameElment.setTextContent(name);
		
		Element authorElement = document.createElement("author");
		authorElement.setTextContent(author);
		
		book.setAttributeNode(priceAttr);
		book.appendChild(nameElment);
		book.appendChild(authorElement);
		
		return book;
	}
}
